package com.ufo.store.management.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.Isszmbalv3StockSalesRecyclerViewAdapter;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Isszmbalv3SaleDetailInfo;
import com.ufo.store.management.ui.fragment.Isszmbalv3CalenderFragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 *  作者：taoli on 2017/7/20 0020 09:01
 *  
 */
public class Isszmbalv3StockSalesActivity extends BaseActivity{
    private static final String TAG = StockSalesActivity.class.getSimpleName();
    private Toolbar toolbar;
    private String mSaleStockno = null;
    private String mSaleStockname = null;
    private String mSearchBranchNo = "";
    private TextView title_tv = null;
    private RelativeLayout mHorizontalBarChartRl = null;
    private RelativeLayout mContentRl = null;
    private RelativeLayout mProcessTipLy = null;
    private LinearLayout mGetFailedLl = null;

    private RecyclerView mRecyclerView = null;
    private Isszmbalv3StockSalesRecyclerViewAdapter mIsszmbalv3StockSalesRecyclerViewAdapter = null;

    private HorizontalBarChart mHorizontalBarChart = null;

    private float mGross = 0;
    private float mRetained = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_back_selector);
        toolbar.setOnMenuItemClickListener(onMenuItemClickListener);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.stocksales_menu, menu);
        return true;
    }

    private Toolbar.OnMenuItemClickListener onMenuItemClickListener=new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()){
                case R.id.action_refresh:
                    new GetIsszmbalv3SaleDetailInfoTask().execute(mSaleStockno);
                    break;
            }
            return true;
        }
    };

    private void initData(){
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mSaleStockno =  bundle.getString("StockNo");
                mSaleStockname =  bundle.getString("StockName");
            }
        }
    }

    private void initView() {
        setContentView(R.layout.activity_isszmbalv3_stock_sales);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(mSaleStockname.trim());
        mHorizontalBarChartRl = (RelativeLayout) findViewById(R.id.chart_rl);
        mContentRl = (RelativeLayout) findViewById(R.id.content_rl);
        mProcessTipLy = (RelativeLayout) findViewById(R.id.progress_tip_ly);
        mGetFailedLl = (LinearLayout) findViewById(R.id.get_fail_tip_ly);

        mRecyclerView = (RecyclerView) findViewById(R.id.sales_recyclerview);
        mIsszmbalv3StockSalesRecyclerViewAdapter = new Isszmbalv3StockSalesRecyclerViewAdapter(Isszmbalv3StockSalesActivity.this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mIsszmbalv3StockSalesRecyclerViewAdapter);
        mIsszmbalv3StockSalesRecyclerViewAdapter.setOnClickListener(new Isszmbalv3StockSalesRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onItemClick(View v, int position) {

            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });

        mHorizontalBarChart = (HorizontalBarChart)findViewById(R.id.chart);
        setupChart();

        new GetIsszmbalv3SaleDetailInfoTask().execute(mSaleStockno);
    }

    private void setupChart() {
        mHorizontalBarChart.getDescription().setText("");
        mHorizontalBarChart.setNoDataText("没有销售记录");//没有数据时显示的文字
        mHorizontalBarChart.setNoDataTextColor(R.color.app_key_color);//没有数据时显示文字的颜色

        mHorizontalBarChart.setDrawBarShadow(false);

        mHorizontalBarChart.setDrawValueAboveBar(true);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mHorizontalBarChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mHorizontalBarChart.setPinchZoom(false);

        // draw shadows for each bar that show the maximum value
        // mHorizontalBarChart.setDrawBarShadow(true);

        // mHorizontalBarChart.setDrawXLabels(false);

        mHorizontalBarChart.setDrawGridBackground(false);

        // mHorizontalBarChart.setDrawYLabels(false);

        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        mHorizontalBarChart.getAxisRight().setEnabled(false);
        mHorizontalBarChart.getAxisLeft().setEnabled(false);

        //左侧纵坐标
        XAxis xl = mHorizontalBarChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setTypeface(tf);
        xl.setDrawAxisLine(false);
        xl.setDrawGridLines(false);
        xl.setGridLineWidth(0.3f);
        xl.setTextColor(Color.parseColor("#5c5c5c"));    //左侧纵坐标的颜色
        xl.setGranularity(1);
        xl.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String str = "";
                if( value == 0 ){
                    str = "总售出";
                }else if( value == 1 ){
                    str = "收益";
                }
                return str;
            }
        });

        //上部横坐标
        YAxis yl = mHorizontalBarChart.getAxisLeft();
        yl.setTypeface(tf);
        yl.setDrawAxisLine(false);
        yl.setDrawGridLines(false);
        yl.setGridLineWidth(0.3f);
        yl.setAxisMinValue(0f); // this replaces setStartAtZero(true)
//        yl.setInverted(true);
        yl.setTextColor(Color.parseColor("#5c5c5c"));    //左侧纵坐标的颜色

        //底部横坐标
        YAxis yr = mHorizontalBarChart.getAxisRight();
        yr.setEnabled(true);
        yr.setTypeface(tf);
        yr.setDrawAxisLine(false);
        yr.setDrawGridLines(false);
        yr.setAxisMinValue(0f); // this replaces setStartAtZero(true)
//        yr.setInverted(true);
        yr.setTextColor(Color.parseColor("#5c5c5c"));    //左侧纵坐标的颜色
        yr.setValueFormatter(new MyYAxisValueValueFormatter());

        //底部说明文字
        Legend l = mHorizontalBarChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        l.setForm(Legend.LegendForm.LINE);
        l.setFormSize(8f);
        l.setXEntrySpace(4f);
        l.setTextColor(Color.parseColor("#5c5c5c"));        //底部说明文字颜色
    }

    private void setChartData() {
        if( mGross == 0 && mRetained == 0 )
            return;
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        yVals1.add(new BarEntry(0, mGross));
        yVals1.add(new BarEntry(1, mGross - mRetained));

        // add a lot of colors
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.parseColor("#ef0505"));
        colors.add(Color.parseColor("#f23030"));

        BarDataSet set1 = new BarDataSet(yVals1, "销售额(元)");
        set1.setColors(colors);
        set1.setValueFormatter(new MyYValueValueFormatter());
        set1.setValueTextColor(Color.parseColor("#5c5c5c"));

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);
        data.setValueTypeface(tf);
        data.setBarWidth(0.9f);

        mHorizontalBarChart.setData(data);
        mHorizontalBarChart.animateY(2500);
    }

    private class MyYAxisValueValueFormatter implements IAxisValueFormatter {
        public MyYAxisValueValueFormatter() {
        }

        @Override
        public String getFormattedValue(float value, AxisBase yAxis) {
            DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
            return "¥" + decimalFormat.format(value);
        }
    }

    private class MyYValueValueFormatter implements IValueFormatter {
        public MyYValueValueFormatter () {
        }

        @Override
        public String getFormattedValue(float var1, Entry var2, int var3, ViewPortHandler var4) {
            DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
            return "¥" + decimalFormat.format(var1);
        }
    }

    private class GetIsszmbalv3SaleDetailInfoTask extends AsyncTask<String, Void, List<Isszmbalv3SaleDetailInfo>> {
        public GetIsszmbalv3SaleDetailInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mGross = 0;
            mRetained = 0;
        }

        @Override
        protected List<Isszmbalv3SaleDetailInfo> doInBackground(String... params) {
            String stockno = params[0];
            List<Isszmbalv3SaleDetailInfo> saleDetailList = new ArrayList<>();
            if( BarApplication.getInstance().mDatabaseIsSqlServer) {
                saleDetailList = DatabaseManager.getIsszmbalv3SaleDetailInfoFromSqlServer(Isszmbalv3StockSalesActivity.this, 2, stockno, mSearchBranchNo);
            }else {
                saleDetailList = DatabaseManager.getIsszmbalv3SaleDetailInfoFromLocal(Isszmbalv3StockSalesActivity.this, 2, stockno, mSearchBranchNo);
            }
            for (Isszmbalv3SaleDetailInfo info : saleDetailList) {
                mGross = mGross + info.saleDetailPrice * info.saleDetailQuantity;
                mRetained = mRetained + info.saleDetailCost * info.saleDetailQuantity;
            }
            return saleDetailList;
        }

        @Override
        protected void onPostExecute(List<Isszmbalv3SaleDetailInfo> result) {
            super.onPostExecute(result);
            if( result != null ) {
                if( result.size() != 0 ) {
                    mIsszmbalv3StockSalesRecyclerViewAdapter.addData(result);
                    mIsszmbalv3StockSalesRecyclerViewAdapter.notifyDataSetChanged();
                    mProcessTipLy.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mGetFailedLl.setVisibility(View.GONE);
                }else{
                    mProcessTipLy.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.GONE);
                    mGetFailedLl.setVisibility(View.VISIBLE);
                }
                setChartData();
            }
        }
    }
}
